// https://leetcode.cn/problems/design-add-and-search-words-data-structure/description/?envType=study-plan-v2&envId=top-interview-150

class Node {
public:
    bool isEnd;
    vector<Node*> children;

    Node() {
        isEnd = false;
        children = vector<Node*>(26, nullptr);
    }
};

class WordDictionary {
private:
    Node* root;
public:
    WordDictionary() {
        root = new Node();
    }
    
    void addWord(string word) {
        Node* cur = root;
        for (int i = 0; i < word.size(); i++) {
            if (cur->children[word[i] - 'a'] == nullptr) {
                cur->children[word[i] - 'a'] = new Node();
            }
            cur = cur->children[word[i] - 'a'];
        }
        cur->isEnd = true;
    }
    
    bool search(string word) {
        return dfs(root, word, 0);
    }

    bool dfs(Node* root, string word, int index) {
        if (index == word.size()) {
            return root->isEnd;
        }

        char child = word[index];
        if (child == '.') {
           for (int i = 0; i < 26; i++) {
                Node* childNode = root->children[i];
                if (childNode && dfs(childNode, word, index + 1)) {
                    return true;
                }
            }
        } else if (child >= 'a' && child <= 'z') {
            Node* childNode = root->children[child - 'a'];
            if (childNode && dfs(childNode, word, index + 1)) {
                return true;
            }
        }
        return false;
    }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */